﻿using HZYProject.Core.Repositories;
using HZYProject.Domain;
using System.Linq.Dynamic.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using HZYProject.Data;

namespace HZYProject.Service
{
    public class UserService : IUserService
    {

        private readonly IRepository<User, int> _userRepository;
        private readonly HZYProjectDbContext _dbContext;
        public UserService(IRepository<User, int> userRepository,HZYProjectDbContext dbContext)
        {
            _userRepository = userRepository; _dbContext = dbContext;
        }

        public async Task<PagedResultDto<User>> GetPaginatedResult(GetUserInput input)
        {
            var query = _userRepository.GetAll();

            //搜索
            if (!string.IsNullOrEmpty(input.UserName))
            {
                query = query.Where(x => x.UserName.Contains(input.UserName));
            }
            if (!string.IsNullOrEmpty(input.RealName))
            {
                query = query.Where(x => x.RealName.Contains(input.RealName));
            }

            //统计查询数据的总条数，用于分页计算总页数
            var count = query.Count();
            //根据需求进行排序，然后进行分页逻辑的计算
            query = query.OrderByDescending(x => x.CreateTime).Skip((input.CurrentPage - 1) * input.MaxResultCount).Take(input.MaxResultCount);
            //将查询结果转换为List集合，加载到内存中
            var models = await query.AsNoTracking().ToListAsync();


            var dtos = new PagedResultDto<User>
            {
                TotalCount = count,
                CurrentPage = input.CurrentPage,
                MaxResultCount = input.MaxResultCount,
                Data = models,
                FilterText = input.FilterText,
            };
            return dtos;
        }

        public User GetUser(Guid userId)
        {
            return _userRepository.GetAll().Include("Roles").FirstOrDefault(x => x.UserId == userId);
        }

        public void FenPeiRole(Guid userId, Guid[] roles)
        {           
            var u = _dbContext.Users.Where(x => x.UserId == userId).Include("Roles").FirstOrDefault();
            u.Roles.Clear();
            foreach (var item in roles)
            {
                u.Roles.Add (_dbContext.Roles.FirstOrDefault(x => x.RoleID == item));
            }
            _dbContext.SaveChanges();
        }

    }
}
